#include "preference.h"
#include "ui_preference.h"
#include <QFileDialog>

Preference::Preference(PreferencesService *preS) :
    ui(new Ui::Preference)
{
    ui->setupUi(this);
    this->setWindowFlags(this->windowFlags() &~ Qt::WindowMinMaxButtonsHint);

    /* 初始化 */
    this->preferencesService = preS;
    ui->defaultPath->setPlaceholderText("选择默认路径");
    /* 设置默认路径不可输入 */
    ui->defaultPath->setReadOnly(true);
    /* 设置默认路径 */
    connect(ui->selectDefaultPath, &QPushButton::clicked, this, &Preference::setDefaultPath);
    connect(ui->success, &QPushButton::clicked, this, &QWidget::close);

    this->renderConfigData();
}

Preference::~Preference()
{
    delete ui;
}

/* 设置默认路径 */
void Preference::setDefaultPath(){
    QString fPath; // 暂存原路径
    fPath = QFileDialog::getExistingDirectory(
                this,
                "选择默认路径",
                "/"
                );
    if(fPath != ""){ // 新路径不为空
        this->fPath = fPath;
        ui->defaultPath->setText(this->fPath); // 写入新路径
    }
}

/* 获取并渲染配置文件数据 */
void Preference::renderConfigData(){
    /* 获取当前配置文件默认信息 */
    configData = preferencesService->getPreferencesData();
    /* 渲染配置信息 */
    ui->defaultPath->setText(configData["file-path"]);
    ui->configFileFormat->setCurrentText(this->configData["export-file-format"]);
    /* 写入文件路径 */
    this->fPath = configData["file-path"];

}

/* 更新配置文件数据 */
void Preference::updateConfigData(){
    /* 获取当前配置文件默认信息 */
    this->configData = preferencesService->getPreferencesData();
    /* 修改数据 */
    this->configData["file-path"] = ui->defaultPath->text();
    this->configData["export-file-format"] = ui->configFileFormat->currentText();
    preferencesService->updatePreferences(this->configData);

}

void Preference::closeEvent(QCloseEvent *event){
    this->updateConfigData();
    emit Preference::updateExportData();
}
